package recusive;

/**
 * @author luo
 * @description
 * @since 2022/7/21 17:19
 * leetCode 814
 */
public class PruneTree {

    public static void main(String[] args) {

        TreeNode input = example3();
        TreeNode result = new PruneTree().pruneTree(input);

        System.out.println(result);

    }

    static TreeNode example1() {
        TreeNode root = new TreeNode(1);
        TreeNode child1 = new TreeNode(0);
        root.right = child1;
        child1.left = new TreeNode(0);
        child1.right = new TreeNode(1);
        return root;
    }

    static TreeNode example2() {
        TreeNode root = new TreeNode(1);
        TreeNode left1 = new TreeNode(0);
        left1.left = new TreeNode(0);
        left1.right = new TreeNode(0);
        root.left = left1;

        TreeNode right1 = new TreeNode(1);


        right1.left = new TreeNode(0);
        right1.right = new TreeNode(1);
        root.right = right1;
        return root;
    }

    static TreeNode example3() {
        TreeNode root = new TreeNode(1);
        TreeNode left1 = new TreeNode(1);
        left1.left = new TreeNode(1);
        left1.left.left = new TreeNode(0);
        left1.right = new TreeNode(1);
        root.left = left1;

        TreeNode right1 = new TreeNode(0);


        right1.left = new TreeNode(0);
        right1.right = new TreeNode(1);
        root.right = right1;
        return root;
    }

    public TreeNode pruneTree(TreeNode root) {

        return find(root);
    }

    private TreeNode find(TreeNode node) {
        if (node == null) {
            return null;
        }
        TreeNode leftChild = find(node.left);
        TreeNode rightChild = find(node.right);
        boolean leftValid = leftChild != null;
        if (!leftValid) {
            node.left = null;
        }
        boolean rightValid = rightChild != null;
        if (!rightValid) {
            node.right = null;
        }
        if (leftValid || rightValid) {
            return node;
        } else if (node.val == 1) {
            return node;
        }
        return null;
    }
}
